import { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import axios from "axios"; // Make sure axios is installed

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || "http://localhost:5001";

// Define an interface for the Dataset object
interface Dataset {
  id: string;
  name: string;
  description?: string; // Optional as it has a fallback
  document_count: number;
  created_at: string; // Assuming it"s a string date, will be parsed
  // Add other properties if they exist and are used
}

const DatasetsList = () => {
  const [datasets, setDatasets] = useState<Dataset[]>([]); // Use the Dataset interface here
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null); // Explicitly type error state

  useEffect(() => {
    const fetchDatasets = async () => {
      try {
        setLoading(true);
        const response = await axios.get<{ datasets: Dataset[] }>(`${API_BASE_URL}/datasets`); // Type the expected response
        setDatasets(response.data.datasets || []);
        setError(null);
      } catch (err: any) { // Type err as any or a more specific error type if known
        console.error("Error fetching datasets:", err);
        if (err.response) {
            setError(`Error: ${err.response.status} - ${err.response.data.error || "Server error"}`);
        } else if (err.request) {
            setError("No response from server. Is the backend running?");
        } else {
            setError("Error setting up request.");
        }
      } finally {
        setLoading(false);
      }
    };

    fetchDatasets();
  }, []);

  if (loading) return <p>正在加载知识库...</p>;
  if (error) return <p>加载知识库失败: {error}</p>;

  return (
    <div>
      <h2>知识库列表</h2>
      <Link to="/datasets/new" style={{ marginBottom: "1rem", display: "inline-block" }}>
        创建新知识库
      </Link>
      {datasets.length === 0 ? (
        <p>暂无知识库，请先创建。</p>
      ) : (
        <ul>
          {datasets.map((dataset: Dataset) => ( // Explicitly type dataset here
            <li key={dataset.id}>
              <h3>{dataset.name}</h3>
              <p>{dataset.description || "暂无描述"}</p>
              <p>文档数量: {dataset.document_count}</p>
              <p>创建时间: {new Date(dataset.created_at).toLocaleString()}</p>
              {/* Add link to dataset detail/upload page */}
              <Link to={`/datasets/${dataset.id}/upload`}>上传文档</Link> |
              <Link to={`/datasets/${dataset.id}/retrieve`}> 检索测试</Link>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
};

export default DatasetsList;

